package com.openxt.nbzj.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.openxt.nbzj.R;
import com.openxt.nbzj.activity.AboutUsActivity;
import com.openxt.nbzj.activity.AccountSettingActivity;
import com.openxt.nbzj.activity.HomeActivity;
import com.openxt.nbzj.activity.WebViewActivity;
import com.openxt.nbzj.call.AccessStatisticsManager;
import com.openxt.nbzj.call.HeartBeatManager;
import com.openxt.nbzj.model.ConfigModel;
import com.openxt.nbzj.model.RemotingModel;
import com.openxt.nbzj.remoting.ClientEx;
import com.openxt.nbzj.remoting.RemotingEx;
import com.openxt.nbzj.util.GlideUtil;
import com.openxt.nbzj.util.SystemUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import id.zelory.compressor.Compressor;
import qs.openxt.libs.progress.Wait;
import qs.openxt.libs.remoting.Upload;
import qs.openxt.libs.util.ActivityUtil;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;
import qs.openxt.libs.view.UIAlertView;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by 颖杰_2 on 2016/7/10.
 */
public class OwnerFragment extends OpenxtFragment implements View.OnClickListener, RemotingEx.OnActionListener {

    @BindView(R.id.icon)
    ImageView icon;
    @BindView(R.id.nickname)
    TextView nickname;
    @BindView(R.id.typename)
    ImageView typename;
    @BindView(R.id.account)
    TextView account;

    @BindView(R.id.btn_01)
    RelativeLayout btn_01;
    @BindView(R.id.btn_02)
    RelativeLayout btn_02;
    @BindView(R.id.btn_03)
    RelativeLayout btn_03;
    @BindView(R.id.btn_04)
    RelativeLayout btn_04;
    @BindView(R.id.btn_05)
    RelativeLayout btn_05;
    @BindView(R.id.btn_logout)
    RelativeLayout btn_logout;

    Context mContext = null;
    boolean isLoading = false;
    Handler mHandler = new Handler();
    RemotingModel remotingModel = null;
    private static final int REQUEST_CODE_SELECT = 100;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.owner, container, false);
        ButterKnife.bind(this, view);
        TextView tv = (TextView) view.findViewById(R.id.openxt_title);
        tv.setText("个人中心");

        LinearLayout btn = (LinearLayout) view.findViewById(R.id.openxt_title_left);
        btn.setVisibility(View.GONE);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext = getActivity();
        remotingModel = new RemotingModel(mContext);

        btn_01.setOnClickListener(this);
        btn_02.setOnClickListener(this);
        btn_03.setOnClickListener(this);
        btn_04.setOnClickListener(this);
        btn_05.setOnClickListener(this);
        btn_logout.setOnClickListener(this);

        /*String img = "Content/images/gr.jpg";
        icon.setImageBitmap(SystemUtil.getImageFromAssetsFile(img, mContext));*/
        icon.setOnClickListener(this);
    }

    @Override
    public void refresh() {
        AccessStatisticsManager.instance().start(mContext, "#/center", true);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                initViews();
            }
        }, 0);
    }

    @Override
    public void willBeDisplayed() {

    }

    private void initViews() {
        String val = Utils.getLocalStorage(mContext, ConfigModel.LOGIN_NATIVE);
        if (StringUtil.isNull(val))
            return;
        JSONObject info = JSON.parseObject(val);
        final JSONObject UserInfo = info.getJSONObject("UserInfo");

        nickname.setText(UserInfo.getString("NICKNAME"));
        account.setText(UserInfo.getString("Account"));
        String $typename = UserInfo.getString("TYPENAME");
        if ("建委用户".equals($typename)) {
            String img = "Content/images/utype_01.png";
            typename.setImageBitmap(SystemUtil.getImageFromAssetsFile(img, mContext));
        } else if ("普通用户".equals($typename)) {
            String img = "Content/images/utype_02.png";
            typename.setImageBitmap(SystemUtil.getImageFromAssetsFile(img, mContext));
        }
        loadImg(mContext, UserInfo.getString("HEADPORTRAIT"), icon);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_01) {//我的消息
            final UIAlertView dialog = new UIAlertView.Builder(mContext)
                    .setTitle(null)
                    .setMessage("功能尚未开放。")
                    .setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).create();
            dialog.setCancelable(false);
            dialog.show();
        } else if (v.getId() == R.id.btn_02) {//我的收藏
            Bundle bundle = new Bundle();
            String RedirectURL = "index.html#/myfav";
            bundle.putString("url", ConfigModel.ROOTPATH + RedirectURL);
            toActivity(WebViewActivity.class, bundle, false);
        } else if (v.getId() == R.id.btn_03) {//我的事项
            Bundle bundle = new Bundle();
            String RedirectURL = "index.html#/myitem";
            bundle.putString("url", ConfigModel.ROOTPATH + RedirectURL);
            toActivity(WebViewActivity.class, bundle, false);
        } else if (v.getId() == R.id.btn_04) {//账户设置
            toActivity(AccountSettingActivity.class);
        } else if (v.getId() == R.id.btn_05) {//关于我们
            toActivity(AboutUsActivity.class);
        } else if (v.getId() == R.id.btn_logout) {//退出登录
            final UIAlertView dialog = new UIAlertView.Builder(mContext)
                    .setTitle("温馨提示")
                    .setMessage("是否确认退出登录？")
                    .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            doLogout();
                        }
                    }).create();
            dialog.setCancelable(false);
            dialog.show();
        } else if (v.getId() == R.id.icon) {
            if (!ActivityUtil.isNetworkAvailable(mContext)) {
                showMsg("无网络，请先查看网络是否正常打开");
                return;
            }
            doPhoto();
        }
    }

    private void doLogout() {
        //清空登录信息 跳转到首页
        ClientEx.CUSTOMERID = null;
        Utils.removeLocalStorage(mContext, ClientEx.CUSTOMERID_KEY);
        Utils.removeLocalStorage(mContext, ConfigModel.LOGIN_NATIVE);

        HeartBeatManager.instance().stop();
        Utils.setLocalStorage(mContext, ConfigModel.HOME_LOADING, "false");

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                ((HomeActivity) getActivity()).setCurrentItem(0);
            }
        }, 300);
    }

    private void doPhoto() {
        Intent intent = new Intent(mContext, ImageGridActivity.class);
        startActivityForResult(intent, REQUEST_CODE_SELECT);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == ImagePicker.RESULT_CODE_ITEMS && data != null && requestCode == REQUEST_CODE_SELECT) {
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            if (images.isEmpty())
                return;
            onPhotoCropped(images.get(0).path);
        }
    }

    private void onPhotoCropped(final String path) {
        Wait.sharedInstance().start(mContext, "正在上传信息..., 请稍后");
        try {
            Compressor.getDefault(mContext)
                    .compressToFileAsObservable(new File(path))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<File>() {
                        @Override
                        public void call(File file) {
                            doUpload(file.getAbsolutePath());
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            Wait.sharedInstance().stopAll();
                            new File(path).delete();
                            showMsg("图片压缩处理失败");
                        }
                    });

        } catch (Exception e) {
            Wait.sharedInstance().stopAll();
            new File(path).delete();
            showMsg("图片压缩处理失败");
        }
    }

    /**
     * 上传头像
     */
    private void doUpload(final String path) {
        try {
            List<String> list = new ArrayList<>();
            list.add(path);
            JSONObject params = new JSONObject();
            params.put("file", list);
            params.put("url", "http://fileupload.openxt.com/ueditor/controller.ashx?action=uploadimage");

            Upload upload = new Upload(mContext, new Upload.OnActionListener() {
                @Override
                public void onActionCompleted(final String reVal) {
                    new File(path).delete();
                    doUpdateHead(reVal);
                }

                @Override
                public void onActionError() {
                    Wait.sharedInstance().stopAll();
                    showMsg("上传头像失败");
                }
            });
            upload.doRequest(params);
        } catch (Exception e) {
            new File(path).delete();
        }
    }

    private void doUpdateHead(String val) {
        try {
            JSONObject json = JSON.parseObject(val);
            if ("SUCCESS".equalsIgnoreCase(json.getString("state"))) {
                String url = json.getString("prefix") + json.getString("url");
                Wait.sharedInstance().start(mContext, "正在保存信息..., 请稍后");
                remotingModel.doCustomerUptImage(this, false, url);
            } else
                showMsg(json.getString("error"));
        } catch (Exception e) {

        }
    }

    @Override
    public void onActionCompleted(String reVal, String actionName) {
        if (actionName.startsWith(ConfigModel.CUSTOMER_UPTIMAGE)) {
            Wait.sharedInstance().stopAll();
            if ("true".equalsIgnoreCase(reVal)) {
                final String url = actionName.replace(ConfigModel.CUSTOMER_UPTIMAGE + "$", "");
                showMsg("头像保存成功");
                try {
                    String val = Utils.getLocalStorage(mContext, ConfigModel.LOGIN_NATIVE);
                    if (StringUtil.isNull(val))
                        return;
                    JSONObject info = JSON.parseObject(val);
                    final JSONObject UserInfo = info.getJSONObject("UserInfo");
                    UserInfo.put("HEADPORTRAIT", url);

                    Utils.setLocalStorage(mContext, ConfigModel.LOGIN_NATIVE, info.toString());

                    loadImg(mContext, url, icon);
                } catch (Exception e) {
                }
            } else
                showMsg("头像保存失败");
        }
    }

    @Override
    public void onActionFailed(String errorVal, String actionName) {
        Wait.sharedInstance().stopAll();
        showMsg(errorVal);
    }

    private void loadImg(Context context, String url, ImageView imageView) {
        Glide.with(context.getApplicationContext())
                .load(url)
                .placeholder(R.mipmap.user)
                .crossFade()
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .skipMemoryCache(false)
                .into(imageView);
    }
}
